package com.xiaopeng.common.httpResult.util;

import com.alibaba.fastjson2.JSON;
import com.xiaopeng.common.httpResult.constant.HttpRequestConstant;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Objects;

/**
 * 打印异常及其 请求参数信息
 * @author xiaopeng
 */
@Slf4j
@Component
public class ExceptionLogUtil {

    /**
     * 打印错误日志
     * @param e
     */
    public static void logErr(Exception e) {
        ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
        HttpServletRequest request = servletRequestAttributes.getRequest();

        //接口类型 及 地址
        String method = request.getMethod();
        String requestURI = request.getRequestURI();

        StringBuilder builder = new StringBuilder();
        builder.append("接口：").append(method).append(" ").append(requestURI);

        // 请求参数Param
        String queryString = request.getQueryString();
        if (StringUtils.isNotEmpty(queryString)){
            try {
                queryString = queryString.replaceAll("&", " , ");
                builder.append(" 请求参数Param: ").append(URLDecoder.decode(queryString, "UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                builder.append(" 请求参数UTF-8解码异常");
            }
        }

        // 请求参数Body - requestBody 由RequestBodyAdviceAdapter写入
        Object requestBody = request.getAttribute(HttpRequestConstant.REQUEST_BODY);
        if (Objects.nonNull(requestBody)) {
            builder.append(" 请求参数Body: ").append(JSON.toJSONString(requestBody));
        }

        log.error(builder.toString(), e);
    }

}
